<template>
  <div>
    <a-table
      ref="table"
      size="middle"
      :scroll="{x:true}"
      bordered
      rowKey="id"
      :columns="columns"
      :pagination="mypagination"
      :dataSource="dataSource"
      @change="handleTableChange"
      class="j-table-force-nowrap"
     >
      <template slot="htmlSlot" slot-scope="text">
        <div v-html="text"></div>
      </template>


      <span slot="tags" slot-scope="tags">
      <a-tag
        color="blue"
        v-for="tag in tags"
        :key="tag"
      >
        {{ tag }}
      </a-tag>
    </span>
      

      <span slot="action" slot-scope="text, record">
        <a ref="#" @click="showmap(text,record)">浏览</a>

        <a-divider type="vertical" v-if="ismanager"/>
        <a-dropdown>
          <a class="ant-dropdown-link" v-has="'user:manager'">
            更多
            <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item >
              <a @click="showTransfer(record.id,record.sourceType)">授权</a>
            </a-menu-item>
            <!-- 图片上传未完成 -->
            <a-menu-item >
              <a @click="showModal(record)">编辑</a>
            </a-menu-item>

            <a-menu-item >
              <a-popconfirm title="确定删除吗?" @confirm="() => handleMyDelete(record.id,record.sourceType)">
                <a>删除</a>
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </a-table>
    <transfer
    :visible="transferVisible"
    :transferId='transferId'
    @cancel="handleCancelTransfer"
    @create="handleCreateTransfer"
    @targetKeys='targetKeys'
    >
    </transfer>
    <mapModal
      :mapInfo="mapInfo"
      ref="mapModal"
      :visible="visible"
      @cancel="handleCancel"
      @create="handleCreate"
    ></mapModal>
  </div>
</template>

<script>
import '@/assets/less/TableExpand.less'
import Axios from 'axios'
import mapModal from './mapModal'
import transfer from './transfer'
import { Store } from 'vuex'

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
const dataSource = []
let tablemodel = {}


export default {
  
  name: 'mymapbody',
  filters: {
    fmttags(val) {
      for(var i = 0;i < val.length ; i++){
        return val[i];
      }
    },
  },
  // 父组件传来的参数
  props: [
    'typekey',
    'ismanager'
  ],
  components: {
    mapModal,
    transfer,
  },
  data() {
    return {
      listUrl:'/sys/resource/list',
      mytargetKeys:[],
      transferVisible:false,
      transferId:'',
      transferType:'',
      mapInfo:{},
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        tags: [{ required: true, message: '请选择一个标签', trigger: 'change' }],
        desc: [
          { required: true, message: '请输入对资源的描述', trigger: 'blur' },
          { min: 5, message: '请至少输入五个字符', trigger: 'blur' },
        ]},
      visible: false,
      loading: false,
      dataSource,
      maptype:'3',
      description: '资源管理页面',
      islist: true,
      list:[],
      mypagination:{
        pageSizeOptions: ['10', '20', '30'],
        current: 1,
        pageSize: 10,
        total:1,
        showTotal:(total,range) =>{
          console.log(range);
          // return range[0] + '-' +range[1] +'共' +total +'条'
          return '共' +total +'条'
        },
      showSizeChanger:true,
      },
      text:'',

      // 表头
      columns: [
        {
          title: '资源名称',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '类型',
          align: 'center',
          dataIndex: 'sourceType',
        },
        {
          title: '资源时间',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
        },
        {
          title: '发布时间',
          align: 'center',
          dataIndex: 'updateTime',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
        },
        {
          title: '标签',
          align: 'center',
          dataIndex: 'tags',
          scopedSlots: { customRender: 'tags' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
    }
  },
  //监听父组件typekey的变化
  watch:{
    typekey : {handler(n , o) {//箭头函数  不然会发生this改变
      if(n==='cj'){
        this.maptype = '1'
        this.axios.get(this.listUrl,
        {
          params:{
            sourceTypeInt:'1',
            pageNo:'1',
            pageSize:'10',
        } 
        }).then((res) => {
          console.log(res);
          this.dataSource = res.result.content
          this.mypagination.total =res.result.total
          this.mypagination.current = res.result.currentPage
          this.mypagination.pageSize = res.result.pageSize
        })
      }else if(n==='map'){
        this.maptype = '2'
        this.axios.get(this.listUrl,
        {
          params:{
            sourceTypeInt:'2',
            pageNo:'1',
            pageSize:'10',
        } 
        }).then((res) => {
          console.log(res);
          this.dataSource = res.result.content
          this.mypagination.total =res.result.total
          this.mypagination.current = res.result.currentPage
          this.mypagination.pageSize = res.result.pageSize
        })
      }else{
        this.maptype = '3'
        this.axios.get(this.listUrl,
        {
          params:{
            sourceTypeInt:'3',
            pageNo:'1',
            pageSize:'10',
        } 
        }).then((res) => {
          console.log(res);
          this.dataSource = res.result.content
          this.mypagination.total =res.result.total
          this.mypagination.current = res.result.currentPage
          this.mypagination.pageSize = res.result.pageSize
        })
      }},deep: true
    },

  },

  //第一次显示全部资源的第一页
  created() {
    if(!this.ismanager){
      this.listUrl='/sys/resource/myList'
    }
    this.axios.get(this.listUrl,
    {
      params:{
        sourceTypeInt:'3',
        pageNo:'1',
        pageSize:'10'
    } 
    }).then((res) => {
      console.log(res)
      if(res.result==null){
        this.$message.error(res.message);
      }else{
      this.dataSource = res.result.content
      this.mypagination.total = res.result.total
      this.mypagination.current =res.result.currentPage
      this.mypagination.pageSize =res.result.pageSize
      }
    })   
  },
  computed: {
    // importExcelUrl: function () {
    //   return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    // },

  },
  
  methods: {
    // 搜索--给父组件调用
    searchMap(text){
      this.text=text
      this.axios.get(this.listUrl,
        {
          params:{
            keywords:text,
            sourceTypeInt:this.maptype,
            pageNo:'1',
            pageSize:'10',
          } 
        }).then((res) => {
          // console.log(res)
          this.dataSource = res.result.content
          this.mypagination.total =res.result.total
          this.mypagination.current =res.result.currentPage
          this.mypagination.pageSize =res.result.pageSize

      })
    },
    //分页
    handleTableChange(pagination,filters,sorter){
      if(this.text){
        this.axios.get(this.listUrl,
        {
          params:{
            keywords:this.text,
            sourceTypeInt:this.maptype,
            pageNo:pagination.current,
            pageSize:pagination.pageSize,
        } 
        }).then((res) => {
          this.dataSource = res.result.content
          this.mypagination.current =res.result.currentPage
          this.mypagination.pageSize =pagination.pageSize

      })
      }else{
        this.axios.get(this.listUrl,
        {
          params:{
            sourceTypeInt:this.maptype,
            pageNo:pagination.current,
            pageSize:pagination.pageSize,
            
        } 
        }).then((res) => {
          
          this.dataSource = res.result.content
          this.mypagination.current =res.result.currentPage
          this.mypagination.pageSize =pagination.pageSize

      })
      }
    },
    //浏览
    showmap(text,record){
      this.$root.$emit('mysourceType',record.sourceType)
      if(record.sourceType == '地图服务'){
        
        let url2D = this.$router.resolve({path:'/Map/show2D',query: {id:record.id}});
        window.open(url2D.href,'blank')
      }else{
        let url3D = this.$router.resolve({path:'/Map/show3D',query: {url:record.url}});
        window.open(url3D.href,'blank')
      }
    },
    initDictConfig() {},
    // 删除操作
    handleMyDelete(id,sourceType) {
      var delobj = {
        id: id,
        sourceType:sourceType,
      };
      this.axios
        .delete('/sys/resource/deleteResourceById', {data:delobj})
        .then((res) => {
          if(res.success){
            this.$message.success('删除成功');
            this.searchMap('')
          }else{
            this.$message.error('删除失败');
          }
        })
    },
    //授权弹窗
    showTransfer(id,type){
      this.transferVisible = true;
      this.transferId = id
      this.transferType = type
    },
    handleCancelTransfer(){
      this.transferVisible = false;
    },
    targetKeys(value){
      this.mytargetKeys = value
    },
    handleCreateTransfer(){
      let obj ={
        resourceId:this.transferId.toString(),
        sourceType:this.transferType,
        tenantIds:this.mytargetKeys
      }
      this.axios.post('/sys/resource/authResourceToTenant',obj).then(res=>{
        if(res.success){
          this.$message.success('授权成功');
          this.transferVisible = false;
        }else{
          this.$message.error('授权失败');
          this.transferVisible = false;
        }
      })
    },
    //编辑表单弹窗
    showModal(record) {
      this.visible = true;
      this.mapInfo = record;
    },
    handleCancel() {
      this.visible = false;
      this.$refs.mapModal.form.resetFields()
    },
    //编辑
    handleCreate() {
      const form = this.$refs.mapModal.form;
      form.validateFields((err, values) => {
        if (err) {
          this.$message.error('修改的值不能为空');
        }else{
          this.axios
            .put('/sys/resource/edit', 
              this.tablemodel = {
                id: this.mapInfo.id,
                name: values.name,
                sourceType:this.mapInfo.sourceType,
                tags: values.tags,
                description: values.description,
              }
            )
            .then((res) => {
              if(res.success){
                form.resetFields();
                this.visible = false
                this.$message.success('修改成功');
                this.searchMap('')
              }else{
                this.$message.error('修改失败');
                form.resetFields();
              }
            }).catch((err)=>{
              console.log(err)
            })
        }       
      });
    },

    
    handleChangetype(value) {
    },
  },
}
</script>


<style scoped >
.myimg{
  width: 128px;
  height: 128px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>